package org.zzh.service.system.user;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zzh.dao.common.PageBean;
import org.zzh.dao.mapper.PeRoleMapper;
import org.zzh.dao.mapper.PeUserMapper;
import org.zzh.domain.system.user.PeUser;

import java.util.List;

@Service
public class PeUserServiceImpl implements PeUserService {

    @Autowired
    private PeUserMapper userMapper;

    @Autowired
    private PeRoleMapper roleMapper;

    @Override
    public PageBean<PeUser> list(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page, pageSize);
        List<PeUser> list = userMapper.list(name);
        PageInfo<PeUser> userPageInfo = new PageInfo<>(list);
        PageBean<PeUser> pageBean = new PageBean<>();
        pageBean.setData(userPageInfo.getList());
        pageBean.setTotalCount((int) userPageInfo.getTotal());
        pageBean.setTotalPage(userPageInfo.getPages());
        pageBean.setPage(page);
        pageBean.setPageSize(pageSize);
        return pageBean;
    }

    @Override
    public PeUser findById(String id) {
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public void add(PeUser user) {
        user.setCreateTime(new java.util.Date());
        userMapper.add(user);
    }


    @Override
    @Transactional
    public void update(PeUser user) {
        user.setUpdateTime(new java.util.Date());
        userMapper.update(user);
    }


    @Override
    @Transactional
    public void deleteList(String[] ids) {
        roleMapper.deleteRoleUserList(ids);
        userMapper.deleteList(ids);
    }


    @Transactional
    @Override
    public void changeRole(String[] roleIds, String userId) {
        roleMapper.clearUserRole(userId);
        roleMapper.addList(roleIds, userId);
    }

    @Override
    public PeUser findByName(String name) {
        return userMapper.findByName(name);
    }

    @Override
    public PeUser findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

}
